package com.zw.yzk.kabu.data.repository;

import com.zw.yzk.kabu.data.network.task.Task;
import com.zw.yzk.kabu.data.cache.db.DataBaseManager;
import com.zw.yzk.kabu.data.cache.db.User;
import com.zw.yzk.kabu.data.cache.store.UserStore;
import com.zw.yzk.kabu.data.network.ServiceGenerator;
import com.zw.yzk.kabu.data.network.entity.RefreshUserInfoEntity;
import com.zw.yzk.kabu.data.network.service.RefreshUserInfoService;

import javax.inject.Inject;

import rx.Observable;
import rx.functions.Func1;

/**
 * Created by zhanwei on 2016/12/24.
 */

public class RefreshUserInfoRepository extends CommonRepository {

    @Inject
    UserStore userStore;

    @Inject
    public RefreshUserInfoRepository() {
    }

    @Override
    protected Observable connectServer(Task task) {
        RefreshUserInfoService service = ServiceGenerator.createService(RefreshUserInfoService.class);
        return service.refreshUserInfo(task.userId, task.accessToken);
    }

    @Override
    protected Func1<RefreshUserInfoEntity, Observable> getServerData() {
        return new Func1<RefreshUserInfoEntity, Observable>() {
            @Override
            public Observable call(RefreshUserInfoEntity entity) {
                updateUserInfo(entity);
                return Observable.just(entity);
            }
        };
    }

    /**
     * 更新个人信息
     *
     * @param entity
     */
    private void updateUserInfo(RefreshUserInfoEntity entity) {
        User user = DataBaseManager.getInstance().getLoginUser();
        if (user == null) {
            return;
        }
        user.setUserId(entity.result.userId);
        user.setNickName(entity.result.nickName);
        user.setHeadUrl(entity.result.head);
        user.setIntroduction(entity.result.introduction);
        user.setSex(entity.result.sex);
        user.setTotalFollow(entity.result.totalFollow);
        user.setTotalFans(entity.result.totaFans);
        user.setHasShop(entity.result.hasShop == 1);
        user.setTotalCollectCosplay(entity.result.totalCollectcosplay);

        userStore.updateUserInfo(user);
    }

}
